package com.ice.base.model;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.ice.base.util.BaseUtil;
import com.ice.base.util.BeanRefUtil;
import com.ice.base.util.JwtUtil;
import lombok.Data;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Date;

@Component
@Data
public class BaseModel implements Serializable {

    private String id;

    private String create_by;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date createTime;

    private Integer status;



    //初始化对象
    public void init(BaseModel baseModel) {
        baseModel.setCreate_by(getUserName());
        baseModel.setCreateTime(new Date());
        baseModel.setStatus(1);//数据默认状态
    }
    //初始化对象
    public void initBase(BaseModel baseModel) {
        baseModel.setCreateTime(new Date());
        baseModel.setStatus(1);//数据默认状态
    }



    private String getUserName() {
        String username = "sys";
        Subject subject = null;
        try {
            subject = SecurityUtils.getSubject();
        } catch (UnavailableSecurityManagerException e) {
            username = "api用户";
        }
        if (subject != null) {
            if (subject.getPrincipal() != null) {
                SysLoginModel sysLoginModel = (SysLoginModel) subject.getPrincipal();
                username = sysLoginModel.getUserName();
            }
        }
        return username;
    }

    private String getUserName(HttpServletRequest request) {
        String username = "sys";
        Subject subject = null;
        try {
            subject = SecurityUtils.getSubject();
        } catch (UnavailableSecurityManagerException e) {
            username = "api用户";
        }
        if (subject != null) {
            if (subject.getPrincipal() != null) {
                SysLoginModel sysLoginModel = (SysLoginModel) subject.getPrincipal();
                username = sysLoginModel.getUserName();
            }
        } else {
            String token = request.getHeader("Authentication");
            if (token != null) {
                username = JwtUtil.verifyToken(token);
            }
        }

        return username;
    }

    /**
     * 插入
     *
     * @param request
     * @param baseModel
     */
    public void getInstanceForInsert(HttpServletRequest request, BaseModel baseModel) {
        init(baseModel);
        BeanRefUtil.getInstanceByRequest(request, baseModel, true);
    }


    public void getInstanceForSelect(HttpServletRequest request, BaseModel baseModel) {
        BeanRefUtil.getInstanceByRequest(request, baseModel, false);
    }






}

